package com.common.app.utls

import com.common.app.data.repository.SseApi
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：18/6/2025
 *
 * 描述：SSE (Server-Sent Events) 管理器，处理SSE连接和事件流
 *
 * 修订历史：
 *
 */
class SseManager(dataType: String? = "", staTime: String? = "", endTime: String? = "") {
    private var sseJob: Job? = null

    private val _sseEvents = MutableSharedFlow<SseEvent>()
    val sseEvents: SharedFlow<SseEvent> = _sseEvents.asSharedFlow()
    var dataType: String? = dataType
    var staTime: String? = staTime
    var endTime: String? = endTime

    /**
     * 开始SSE连接
     */
    fun startSseConnection(scope: CoroutineScope) {
        sseJob?.cancel()

        sseJob = scope.launch(Dispatchers.IO) {
            try {
                SseApi.getSseFlow2(dataType, staTime, endTime)
                    .catch { error ->
                        _sseEvents.emit(SseEvent.Error(error.message ?: "Unknown error"))
                    }
                    .collect { data ->
                        _sseEvents.emit(SseEvent.Data(data))
                    }
            } catch (e: Exception) {
                _sseEvents.emit(SseEvent.Error(e.message ?: "Connection failed"))
            }
        }
    }

    /**
     * 停止SSE连接
     */
    fun stopSseConnection() {
        sseJob?.cancel()
        sseJob = null
    }

    /**
     * SSE事件类型
     */
    sealed class SseEvent {
        data class Data(val content: String) : SseEvent()
        data class Error(val message: String) : SseEvent()
        object Connected : SseEvent()
        object Disconnected : SseEvent()
    }
}